package logic

import (
	"ViewSrv/global/model"
	"ViewSrv/internal/svc"
	"ViewSrv/view"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type ViewLenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewViewLenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ViewLenLogic {
	return &ViewLenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ViewLenLogic) ViewLen(in *view.ViewLenRequest) (*view.ViewLenResponse, error) {
	// todo: add your logic here and delete this line
	var VideoLogLen model.VideoLogLen
	if err := model.DB.Where("user_id = ? and video_id = ?", in.UserId, in.VideoId).Find(&VideoLogLen).Error; err != nil {
		return nil, err
	}
	if VideoLogLen.Len == 0 {
		VideoLogLen = model.VideoLogLen{
			VideoId: int(in.VideoId),
			UserId:  int(in.UserId),
			Len:     int(in.VideoLen),
		}
		if err := model.DB.Create(&VideoLogLen).Error; err != nil {
			return nil, err
		}
	} else {
		VideoLogLen.Len = int(in.VideoLen)
		if err := model.DB.Updates(&VideoLogLen).Error; err != nil {
			return nil, err
		}
	}
	return &view.ViewLenResponse{}, nil
}
